<script setup name="CustomerInformation">
import customerServices from '@/api/customerInformation/index.js'
import userServices from '@/api/user/user.js'
import postalCodeJson from '@/assets/json/postalCode.json'
import BaseForm from '@/components/BaseForm/BaseForm.vue'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { useAreaData } from '@/hooks/useAreaData.js'
import useUserStore from '@/store/modules/user.js'
import { formatDate } from '@/utils/dayjs.js'
import { useDict } from '@/utils/dict.js'
import { deepClone, tableCheckChane } from '@/utils/index.js'
import { checkPermissions } from '@/utils/permission.js'
import {
  isEmail,
  isValidMobile,
} from '@/utils/validate.js'
import {
  Delete,
} from '@element-plus/icons-vue'
import Message from 'vue-m-message'
import { useRouter } from 'vue-router'
const {
  fetchCityData,
  areaList,
  findAreaNamesByCode
} = useAreaData()
const { customer_type } = useDict('customer_type')
const customertypeHidden = ref('1')
const tableData = ref([])
const customerName = ref([])
const queryParam = ref({})
const ids = ref([])
const btnLoad = ref(false)
const updateDialogVisible = ref(false)
const updateDialogTitle = ref('添加')
const dutyList = ref([])
const formDisabled = ref(false)

const formLoading = ref(false)
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const router = useRouter()
// const areaList = ref([])
const searchConfig = reactive([
  {
    label: '客户名称',
    field: 'customerName',
    type: 'input',
    defaultShow: true,
  },
  {
    label: '客户类型',
    field: 'customerType',
    type: 'select',
    options: {
      data: customer_type,
      label: 'label',
      value: 'value',
      key: 'value',
    },
    defaultShow: true,
  },
  {
    label: '所属区域',
    field: 'customerName',
    type: 'custom',
    defaultShow: true,
  },
  {
    label: '证件号码',
    field: 'customerIdentity',
    type: 'input',
    defaultShow: true,
  },
])
const tableColumns = reactive([
  { type: 'checkbox', width: 50 },
  { type: 'seq', align: 'center', width: 50 },
  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'customerType',
    title: '客户类型',
    align: 'center',
    minWidth: 80,
    slots: { default: 'customerType' },
    showOverflow: 'tooltip',
  },
  {
    field: 'customerIdentity',
    title: '证件号码',
    align: 'center',
    minWidth: 180,
    showOverflow: 'tooltip',
  },
  {
    field: 'linkman',
    title: '联系人',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'phone',
    title: '联系人电话',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'nickName',
    title: '主对接人',
    align: 'center',
    minWidth: 100,
  },
  {
    field: 'secNickName',
    title: '对接协助人',
    align: 'center',
    minWidth: 120,
  },
  {
    field: 'locationArea',
    title: '所属区域',
    align: 'center',
    minWidth: 240,
    showOverflow: 'tooltip',
  },
  {
    field: 'address',
    title: '详细地址',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'socialStaffNum',
    title: '参保人数',
    align: 'center',
    minWidth: 80,
    showOverflow: 'tooltip',
  },
  {
    field: 'businessScope',
    title: '经营范围',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'mail',
    title: '客户邮箱',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'registDate',
    title: '注册时间',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
    formatter: ({ cellValue }) => {
      return cellValue ? cellValue.split(' ')[0] : ''
    },
  },
  {
    field: 'registFund',
    title: '注册资金',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'actualCapital',
    title: '实缴资金',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'compType',
    title: '公司类型',
    align: 'center',
    minWidth: 130,
    showOverflow: 'tooltip',
  },
  {
    field: 'industry',
    title: '所属行业',
    align: 'center',
    minWidth: 130,
    showOverflow: 'tooltip',
  },
  {
    field: 'postalCode',
    title: '邮政编码',
    align: 'center',
    minWidth: 130,
    showOverflow: 'tooltip',
  },
  {
    field: 'bankAccount',
    title: '开户行账号',
    align: 'center',
    minWidth: 180,
    showOverflow: 'tooltip',
  },
  {
    field: 'bankName',
    title: '开户行名称',
    align: 'center',
    minWidth: 180,
    showOverflow: 'tooltip',
  },
  {
    field: 'invoicePhone',
    title: '开票电话',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'remark',
    title: '备注',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'operate',
    title: '操作',
    align: 'center',
    minWidth: checkPermissions(['system:customerInformation:finance']) ? 330 : 100,
    fixed: 'right',
    slots: { default: 'operate' },
  },
])

const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

const updateFormList = ref([
  {
    label: '客户类型',
    field: 'customerType',
    type: 'custom',
    slotName: 'customerType',
    rules: [{ required: true, message: '请选择客户类型', trigger: 'blur' }],
    span: 24,
  },
  // {
  //   label: '申请人类型',
  //   field: 'applyType',
  //   type: 'select',
  //   rules: [{ required: true, message: '请选择申请人类型', trigger: 'blur' }],
  // },
  {
    label: '客户名称',
    field: 'customerName',
    type: 'custom',
    slotName: 'customerName',
    rules: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    span: 24,
  },
  // {
  //   label: '国籍或地区',
  //   field: 'customerIdentity',
  //   type: 'select',
  //   span: 12,
  // },
  // {
  //   label: '证件类型',
  //   field: 'customerIdentityType',
  //   type: 'select',
  //   span: 12,
  // },
  {
    label: '证件号码',
    field: 'customerIdentity',
    type: 'input',
    rules: [
      {
        required: true,
        message: '请输入证件号码',
        trigger: 'blur',
      },
      // {
      //   validator: (rule, value, callback) => {
      //     if (!isIdCardNo(value) && !isValidCreditCode(value)) {
      //       callback(new Error('请输入正确的证件号码'))
      //     }
      //     else {
      //       callback()
      //     }
      //   },
      // },
    ],
    span: 12,
  },
  {
    label: '所属区域',
    field: 'locationArea',
    type: 'cascader',
    options: {
      data: areaList,
    },
    props: {
      label: 'name',
      value: 'code',
    },
    rules: [{ required: true, message: '请选择所属区域', trigger: 'change' }],
    span: 12,
  },
  // {
  //   label: '城区（乡）、街道、门牌号：',
  //   field: 'cityAddress',
  //   type: 'input',
  //   span: 12,
  // },
  {
    label: '详细地址',
    field: 'address',
    type: 'input',
    span: 12,
  },
  {
    label: '参保人数',
    field: 'socialStaffNum',
    type: 'input',
    span: 12,
  },
  {
    label: '经营范围',
    field: 'businessScope',
    type: 'text',
    maxlength: 260,
    span: 12,
  },
  {
    label: '注册资金',
    field: 'registFund',
    type: 'number',
    span: 12,
  },
  {
    label: '实缴资金',
    field: 'actualCapital',
    type: 'number',
    span: 12,
  },
  {
    label: '公司类型',
    field: 'compType',
    type: 'input',
    span: 12,
  },
  {
    label: '所属行业',
    field: 'industry',
    type: 'input',
    span: 12,
  },
  {
    label: '邮政编码',
    field: 'postalCode',
    type: 'input',
    disabled: true,
    span: 12,
  },
  {
    label: '联系人',
    field: 'linkman',
    type: 'input',
    span: 12,
    rules: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  },
  {
    label: '联系人电话',
    field: 'phone',
    type: 'number',
    rules: [
      {
        required: true,
        message: '请输入联系人电话',
        trigger: 'blur',
      },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
          }
          else if (!isValidMobile(value)) {
            callback(new Error('请输入正确的手机号格式'))
          }
          else {
            callback()
          }
        },
      },
    ],
    span: 12,
  },
  {
    label: '客户邮箱',
    field: 'mail',
    type: 'input',
    rules: [
      {
        required: true,
        message: '请输入客户邮箱',
        trigger: 'blur',
      },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
          }
          else if (!isEmail(value)) {
            callback(new Error('请输入正确的邮箱格式'))
          }
          else {
            callback()
          }
        },
      },
    ],
    span: 12,
  },
  {
    label: '注册时间',
    field: 'registDate',
    type: 'date',
    span: 12,
  },
  {
    label: '开户行账号',
    field: 'bankAccount',
    type: 'input',
    span: 12,
  },
  {
    label: '开户行名称',
    field: 'bankName',
    type: 'input',
    span: 12,
  },
  {
    label: '开票电话',
    field: 'invoicePhone',
    type: 'number',
    rules: [
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
          }
          else if (!isValidMobile(value)) {
            callback(new Error('请输入正确的手机号格式'))
          }
          else {
            callback()
          }
        },
      },
    ],
    span: 12,
  },
  {
    label: '主对接人',
    field: 'dutyId',
    type: 'select',
    options: {
      data: dutyList,
      label: 'nickName',
      value: 'userId',
      key: 'userId',
    },
    rules: [{ required: true, message: '请选择主对接人', trigger: 'change' }],
    span: 12,
  },
  {
    label: '对接协助人',
    field: 'secDutyId',
    type: 'select',
    options: {
      data: dutyList,
      label: 'nickName',
      value: 'userId',
      key: 'userId',
    },
    span: 24,
  },
  {
    label: '备注',
    field: 'remark',
    type: 'textarea',
    span: 24,
  },
])
const updateFormModel = ref({})

onMounted(async () => {
  btnLoad.value = true
  fetchCityData()
  getCustomerInformationData()
})

function getCustomerInformationData() {
  const formData = {
    ...queryParam.value,
    pageSize: pagerConfig.value.pageSize,
    pageNum: pagerConfig.value.currentPage,
  }
  const userInfo = userStore.userInfo
  customerServices.list(formData).then((res) => {
    tableData.value = res.rows
    pagerConfig.value.total = res.total
    btnLoad.value = false
  })
  userServices.getSalesmanList().then((res) => {
    dutyList.value = res.data
    const findData = dutyList.value.find(
      item => item.userId === userInfo.userId,
    )
    if (findData) {
      updateFormModel.value.dutyId = findData.userId
    }
  })
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getCustomerInformationData()
}

function handleCheckChange(data) {
  ids.value = tableCheckChane(data, 'customerId', ids.value)
}

function handleGoPage(row, url) {
  router.push({
    path: `/peoples/${url}`,
    query: { customerId: row.customerId },
  })
}

function handleSearch(e, type) {
  if (type === 'reset') {
    customerName.value = []
  }
  queryParam.value = {
    locationArea: findAreaNamesByCode(customerName.value).join('/'),
    registerDateMin: e.registDate ? e.registDate[0] : null,
    registerDateMax: e.registDate ? e.registDate[1] : null,
    ...e,
  }
  delete queryParam.value.registDate
  getCustomerInformationData()
}

function handleAdd() {
  customertypeHidden.value = '1'
  updateFormModel.value.customerType = '1'
  updateDialogVisible.value = true
}

function handleUpdateSubmit(e) {
  const cityName = findAreaNamesByCode(e.locationArea)
  const params = {
    ...e,
    locationArea: cityName.join('/'),
    registDate: e.registDate
      ? `${formatDate(e.registDate, 'YYYY-MM-DD')} 00:00:00`
      : null,
    localProvinceCode: e.locationArea[0],
    localCityCode: e.locationArea[1],
    localAreaCode: e.locationArea[2],
  }
  if (params?.customerId) {
    customerServices.update(params).then((res) => {
      const { code } = res
      if (code === 200) {
        Message.success('修改成功')
        handleReset()
        getCustomerInformationData()
      }
    })
  }
  else {
    customerServices.add(params).then((res) => {
      const { code } = res
      if (code === 200) {
        Message.success('新增成功')
        handleReset()
        getCustomerInformationData()
      }
    })
  }
}

function handleReset() {
  updateDialogVisible.value = false
  updateFormModel.value = {}
  formDisabled.value = false
  updateDialogTitle.value = '添加'
}

function handleDelete(row) {
  let customerID
  if (row) {
    customerID = row.customerId
  }
  else {
    customerID = ids.value.join(',')
  }
  customerServices.delete(customerID).then((res) => {
    const { code } = res
    if (code === 200) {
      Message.success('删除成功')
      getCustomerInformationData()
    }
  })
}

function handleFormAction(row, type) {
  // row.locationArea = findCodesByNamePath(areaList.value,row.locationArea)
  updateFormModel.value = deepClone(row)
  updateFormModel.value.locationArea = [row.localProvinceCode, row.localCityCode, row.localAreaCode]
  changeCustomerType(updateFormModel.value.customerType)
  formDisabled.value = type === 'view'
  updateDialogTitle.value = type === 'view' ? '查看' : '修改'
  updateDialogVisible.value = true
}

function handleExport() {
  proxy.download(
    'system/customerInformation/export',
    { ...queryParam.value, exportIds: ids.value.join(',') },
    `user_${new Date().getTime()}.xlsx`,
  )
}

function changeCustomerType(value) {
  customertypeHidden.value = value
}

// function getAreaList() {
//   formLoading.value = true
//   areaService.getAreaList().then((res) => {
//     const { code, data } = res
//     areaList.value = data
//     formLoading.value = false
//   })
// }

/**
 * @description 通过code数组获取区域名称数组
 * @param data - 区域数据
 * @param codes - 区域code数组
 * @returns {string[]} - 区域名称数组
 */
// function findAreaNamesByCode(data, codes) {
//   console.log(data)
//   console.log(codes)
//   const result = []
//   // 定义递归函数
//   function search(items) {
//     items.forEach((item) => {
//       if (codes.includes(item.code)) {
//         result.push(item.name)
//       }
//       if (item.children && item.children.length > 0) {
//         search(item.children) // 递归搜索子项
//       }
//     })
//   }
//   search(data) // 从顶层数组开始搜索
//   return result
// }

watch(() => updateFormModel.value, (value, oldValue, onCleanup) => {
  const findLocationAreaIndex = updateFormList.value.findIndex(item => item.field === 'locationArea')
  console.log(updateFormList)
  const companyForm = [
    {
      label: '详细地址',
      field: 'address',
      type: 'input',
      span: 12,
    },
    {
      label: '参保人数',
      field: 'socialStaffNum',
      type: 'input',
      span: 12,
    },
    {
      label: '经营范围',
      field: 'businessScope',
      type: 'text',
      maxlength: 260,
      span: 12,
    },
    // {
    //   label: '客户邮箱',
    //   field: 'mail',
    //   type: 'input',
    //   rules: [
    //     {
    //       validator: (rule, value, callback) => {
    //         if (!value) {
    //           callback()
    //         }
    //         else if (!isEmail(value)) {
    //           callback(new Error('请输入正确的邮箱格式'))
    //         }
    //         else {
    //           callback()
    //         }
    //       },
    //     },
    //   ],
    //   span: 12,
    // },
    // {
    //   label: '注册时间',
    //   field: 'registDate',
    //   type: 'date',
    //   span: 12,
    // },
    {
      label: '注册资金',
      field: 'registFund',
      type: 'number',
      span: 12,
    },
    {
      label: '实缴资金',
      field: 'actualCapital',
      type: 'number',
      span: 12,
    },
    {
      label: '公司类型',
      field: 'compType',
      type: 'input',
      span: 12,
    },
    {
      label: '所属行业',
      field: 'industry',
      type: 'input',
      span: 12,
    },
    {
      label: '邮政编码',
      field: 'postalCode',
      type: 'input',
      span: 12,
    },
  ]
  if (value?.locationArea) {
    const parts = findAreaNamesByCode(value.locationArea)
    const provinceName = parts[0]
    const cityName = parts[1] === '市辖区' ? parts[2] : parts[1]
    if (provinceName && cityName) {
      updateFormModel.value.postalCode = postalCodeJson[provinceName][cityName]
    }
  }
  if (value?.customerType === '2') {
    updateFormList.value = updateFormList.value.filter(item => !companyForm.some(companyItem => companyItem.field === item.field))
  }
  else {
    const findAddress = updateFormList.value.find(item => item.field === 'address')
    if (!findAddress) {
      updateFormList.value.splice(findLocationAreaIndex + 1, 0, ...companyForm)
    }
  }
}, {
  deep: true,
})
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-3">
      <SearchBar :search-config="searchConfig" @search="handleSearch">
        <template #customerName>
          <el-cascader
            v-model="customerName"
            :options="areaList"
            size="default"
            :props="{ value: 'code', label: 'name' }"
            placeholder="请选择所属区域"
            clearable
            class="w-full"
          />
        </template>
      </SearchBar>
    </el-card>
    <el-card shadow="never">
      <div class="toolbar flex mb-1">
        <div class="mb-2 space-x-3">
          <el-button
            v-hasPermi="['system:customerInformation:add']"
            type="primary"
            class="el-gradient-primary"
            @click="handleAdd"
          >
            新增
            <el-icon class="el-icon--right">
              <CirclePlusFilled />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:customerInformation:remove']"
            type="danger"
            class="el-gradient-danger"
            :disabled="ids.length === 0"
            @click="handleDelete(null)"
          >
            删除
            <el-icon class="el-icon--right">
              <Delete />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:customerInformation:export']"
            type="warning"
            class="el-gradient-warning"
            @click="handleExport()"
          >
            导出
            <el-icon class="el-icon--right">
              <FolderAdd />
            </el-icon>
          </el-button>
        </div>
        <RightToolbar />
      </div>
      <vxe-grid
        :row-config="{
          keyField: 'customerId',
        }"
        :data="tableData"
        :columns="tableColumns"
        :pager-config="pagerConfig"
        :column-config="{ resizable: true }"
        header-cell-class-name="headerCellClass"
        :loading="btnLoad"
        max-height="600px"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
      >
        <template #customerType="{ row }">
          <dict-tag :options="customer_type" :value="row.customerType" />
        </template>
        <template #operate="{ row }">
          <div>
            <span v-hasPermi="['system:customerInformation:finance']">
              <el-button
                text
                type="primary"
                size="small"
                @click="handleGoPage(row, 'customerFinanceInformation')"
              >
                财务信息
              </el-button>
            </span>
            <span v-hasPermi="['system:customerInformation:visit']">
              <el-button
                text
                type="primary"
                size="small"
                @click="handleGoPage(row, 'customerVisitRecord')"
              >
                跟进记录
              </el-button>
            </span>
            <span v-hasPermi="['system:customerInformation:query']">
              <el-button
                text
                type="primary"
                size="small"
                @click="handleFormAction(row, 'view')"
              >
                查看
              </el-button>
            </span>
            <!--          <el-divider direction="vertical" /> -->
            <span v-hasPermi="['system:customerInformation:edit']">
              <el-button
                text
                type="success"
                size="small"
                @click="handleFormAction(row, 'edit')"
              >
                修改
              </el-button>
            </span>
            <!--          <el-divider direction="vertical" /> -->
            <span v-hasPermi="['system:customerInformation:remove']">
              <el-popconfirm
                :title="`确认删除 ${row.customerName} 的客户信息吗？`"
                width="200px"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button text size="small" type="danger">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </span>
          </div>
        </template>
      </vxe-grid>
    </el-card>
    <el-drawer
      v-model="updateDialogVisible"
      :destroy-on-close="true"
      class="custom-drawer"
      draggable
      size="47%"
      :show-close="false"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}客户信息
          </span>
        </div>
      </template>
      <BaseForm
        v-loading="formLoading"
        :field-list="updateFormList"
        :model="updateFormModel"
        class="px-5"
        :options="{ disabled: formDisabled, labelWidth: '100px', footerAlign: 'center', footerClass: 'absolute bottom-5 w-full' }"
        element-loading-text="数据加载中..."
        @submit="handleUpdateSubmit"
        @cancel="handleReset"
      >
        <template #customerType>
          <el-select
            v-model="updateFormModel.customerType"
            placeholder="请选择客户类型"
            @change="changeCustomerType($event)"
          >
            <el-option
              v-for="dict in customer_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>
        <template #customerName>
          <el-input
            v-model="updateFormModel.customerName"
            placeholder="请输入用户名称"
          >
            <!--            <template v-if="customertypeHidden === '1'" #append> -->
            <!--              <el-button> -->
            <!--                天眼查 -->
            <!--                <el-icon class="ml-3"> -->
            <!--                  <Search /> -->
            <!--                </el-icon> -->
            <!--              </el-button> -->
            <!--            </template> -->
          </el-input>
        </template>
      </BaseForm>
      <div class="close-btn flex-center" @click="handleReset">
        <el-icon>
          <CloseBold />
        </el-icon>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.close-btn {
  position: fixed;
  top: 50%;
  margin-left: -65px;
  cursor: pointer;
  border: none;
  outline: none;
  width: 45px;
  height: 45px;
  font-size: 22px;
  line-height: 40px;
  text-align: center;
  background-color: var(--el-color-primary);
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);

  &:hover {
    background-color: #f56c6c;

    i {
      transition: transform .5s, -webkit-transform .5s;
      transform: rotate(90deg);
    }
  }
}
</style>
